//单品客户表单表格
var $singleProductCustomerTable = $('#singleProductCustomerTableList');
//查询客户表单表格
var $customerTableList = $('#customerTableList');
//防止表头与表格不对齐
$(window).resize(function () {
    $singleProductCustomerTable.bootstrapTable('resetView');
    $customerTableList.bootstrapTable('resetView');
});

$(function () {
    // 创建时间
    $('.date-input').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    //初始化单品客户表单
    singleProductCustomerTableListInit();
    //初始化查询客户表单
    // customerTableListInit();
    $('#addSingleProductCustomerModel').on('hidden.bs.modal', function () {
        $customerTableList.bootstrapTable('destroy');
    })

    // 高级筛选
    $('#filterContent').on('show.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-close"></i>关闭筛选');
    }).on('hide.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-sort-variant"></i>高级筛选');
    }).on('hidden.bs.collapse', function () {
        resetSingleProductCustomerQueryParams('#filterContent');
    });
});

/**
 * 单品客户表单--分页列表页
 */
function singleProductCustomerTableListInit() {
    //先销毁表格
    $singleProductCustomerTable.bootstrapTable('destroy');
    $singleProductCustomerTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/singleProductCustomer/selectSingleProductCustomerList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'singleProductCustomerId',
        idField: 'singleProductCustomerId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        // 固定列
        fixedColumns: true,
        fixedNumber: 2,
        fixedRightNumber: 1,
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'singleProductCustomerId', visible: false},
            {title: '客户ID', field: 'customerId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '52', formatter: indexFormat},
            {title: '客户名称',field: 'customerName',sortable: true,align: 'left', valign: 'middle',
                formatter: function prompt(value, row, index) {
                    return'<a href="#" onclick=customerDetail("' + row.customerId + '","' + row.singleProductCustomerId +'")>'+value+'</a>';
                }},
            {title: '创建时间', field: 'createTm', sortable: true, align: 'left', width: '200', valign: 'middle'},
            {title: '操作',field: 'operate',align: 'right',events: operateEvents,formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table操作列下拉菜单效果
            tableNav();
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 拼接客户池表格查询条件参数
 */
function advancedQueryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)

    //普通搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    //创建时间(区间)
    params.createTmStart = $('#createTmStart').val();  //创建开始日期
    params.createTmEnd = $('#createTmEnd').val();    //创建截止日期

    return params;
}
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)

    //普通搜索条件
    params.customerName = $.trim($('#customerNameMin').val());//客户名称
    return params;
}

/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    $singleProductCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';

    html += '<div class="dropdown">';
    html += '<button type="button" id="followUp" class="btn btn-default" data-index="' + index + '"><i class="mdi mdi-image-filter-tilt-shift"></i>跟进</button>';
    html += '<ul class="dropdown-menu">';
    html += '<li><a href="JavaScript:void(0);" onclick="callCenter(\''+row.customerId+'\',\''+row.singleProductCustomerId+'\')">线上电话</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'offline\', \''+row.customerId+'\', \''+row.singleProductCustomerId+'\')">线下电话</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'visit\', \''+row.customerId+'\', \''+row.singleProductCustomerId+'\')">拜访</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'WeChat\', \''+row.customerId+'\', \''+row.singleProductCustomerId+'\')">微信交流</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'accompanyingVisit\', \''+row.customerId+'\', \''+row.singleProductCustomerId+'\')">陪访</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'email\', \''+row.customerId+'\', \''+row.singleProductCustomerId+'\')">电子邮件</a></li>';
    html += '</ul>';
    html += '</div>';
    html += '<button class="btn btn-default" id="add"><i class="mdi mdi-plus-circle-outline"></i>创建合同</button>';
    html += '<button class="btn btn-default" id="delete"><i class="mdi mdi-close-circle-outline"></i>删除</button>';
    return html;
}




/**
 * 自定义操作列事件
 */
window.operateEvents = {
    //创建合同点击事件
    'click #add': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe: true,
            title: '创建合同',
            url: "/front/user/customerManager/singleProduct/createContract?singleProductCustomerId=" + row.singleProductCustomerId + "&customerId=" + row.customerId + "&customerName=" + row.customerName
        }, true);
    },
    //删除单品客户
    'click #delete': function (e, value, row, index) {
        deleteSingleProductCustomer(row.singleProductCustomerId);
    }
};

// 跳转线上线下电话跟进   跟进方式：1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
function goOnline(name, id, singleProductCustomerId) {
    var customerId = id;
    var type = '';
    var title = '跟进';
    var source = '2';//从哪跳转到跟进页面（0：线索；1：客户；2:单品客户）
    // 线上电话
    if (name == 'online') {
        type = "1";
        title = '单品客户跟进-线上电话';
    }
    // 拜访
    if (name == 'visit') {
        type = "2";
        title = '单品客户跟进-拜访';
    }
    // 微信
    if (name == 'WeChat') {
        type = "3";
        title = '单品客户跟进-微信交流';
    }
    // 线下电话
    if (name == 'offline') {
        type = "4";
        title = '单品客户跟进-线下电话';
    }
    // 电子邮件
    if (name == 'email') {
        type="5";
        title = '单品客户跟进-电子邮件';
    }
    // 陪访
    if (name == 'accompanyingVisit') {
        type = "6";
        title = '单品客户跟进-陪访';
    }
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : title,
        url : "/front/contactManager/user/clueFollow?type="+ type +"&id="
            + customerId +"&source=" +source +"&singleProductCustomerId=" +singleProductCustomerId
    }, true);
}

function callCenter (customerId,singleProductCustomerId) {
    var contactPersonData = [];
    $.ajax({
        url: "/singleProductCustomer/selectSingleProductCustomerContacts?singleProductCustomerId=" + singleProductCustomerId,
        type: 'GET',
        datatype: 'json',
        async: false,
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    contactPersonData = data.data;
                }
            }
        }
    });
    window.parent.callModal(customerId,contactPersonData,2,singleProductCustomerId);
}

/**
 * 搜索点击事件
 */
function searchSingleProductCustomerList(type,value){
    $('.all').addClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $('.year').removeClass('active-second');
    $("#dateType").val("all");
    if (type === 1) {//普通条件查询
        $singleProductCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetSingleProductCustomerQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#customerNameMin').val('');
        $singleProductCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    }
}

/**
 * 重置单品客户清单查询条件
 */
function resetSingleProductCustomerQueryParams(_this){
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    } else {
        searchForm = $(_this).parents('#filterContent');
    }
    searchForm.find('input[type="text"]').val('');
    /*searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');*/

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        singleProductCustomerTableListInit();
    }
}

//清空所有搜索条件
function clearAllData() {
    //全部 本年 本月 本周
    $('.all').addClass('active-second');
    $('.year').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $("#dateType").val("all");
    //客户名称
    $('#customerName').val('');
    $('#customerNameMin').val('');
    //创建时间
    $('#createTmStart').val('');
    $('#createTmEnd').val('');
    // 清空搜索表单后，重置单品客户
    resetSingleProductCustomerQueryParams('#filterContent');
    $singleProductCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

function addSingleProductCustomerModel(){
    $('#customerNameSearch').val('');
    // $customerTableList.bootstrapTable('refreshOptions', {pageNumber: 1});
    $('#addSingleProductCustomerModel').modal('show');
}

/**
 * 查询客户表单--分页列表页
 */
function customerTableListInit() {
    $customerTableList.bootstrapTable('destroy');//先销毁表格
    $customerTableList.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/customerController/selectSingleProductCustomerList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[10,20,50]",//可供选择的每页的行数
        queryParams: customerQueryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerId', visible: false},
            {title: '客户池ID', field: 'customerPoolId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', width: '52', formatter: indexFormat},
            {title: '客户名称', field: 'customerName', align: 'center', valign: 'middle'},
            {title: '目前状态', field: 'currentStatus', align: 'center', valign: 'middle', formatter: currentStatusFormat},
            {title: '操作', field: 'operate', align: 'right', events: operateEvents,
                formatter: function (value,row,index) {
                    var html = '';
                    if (row.currentStatus == 0) {
                        html += '<button type="button" class="btn btn-default" onclick="receiveCustomer(\'' + row.customerId + '\', \'' + row.customerPoolId + '\')"><i class="mdi mdi-stackoverflow"></i>一键领取</button>';
                    } else {
                        html += '<button type="button" class="btn btn-default" onclick="addSingleProductCustomer(\'' + row.customerId + '\')"><i class="mdi mdi-plus"></i>创建单品客户</button>';
                    }
                    return html;
                }
            }
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录，请输入客户名称进行查询！';
        }
    });
}

/**
 * 目前状态
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function currentStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "未领取";
    } else if (1 == value) {
        return "已领取";
    } else if (2 == value) {
        return "已分配";
    } else if (3 == value){
        return "自建客户";
    }
}
//搜索条件
function customerQueryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //普通搜索条件
    params.customerName = $('#customerNameSearch').val();//客户名称
    return params;
}
//搜索
function searchCustomer() {
    $customerTableList.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: customerQueryParams});
}
//新增单品客户
function addSingleProductCustomer(customerId) {
    $.alert({
        title: '提示',
        content: "确定要新增单品客户吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/singleProductCustomer/addSingleProductCustomer",
                        data: {
                            customerId: customerId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.data == 'C00000') {
                                $.alert('新增成功!');
                                $('#customerNameSearch').val('');
                                $('#addSingleProductCustomerModel').modal('hide');
                                $singleProductCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else if (data.data == 'C00001') {
                                $.alert('单品客户已存在!');
                            } else {
                                $.alert('新增失败！');
                            }
                        },
                        error: function () {
                            $.alert('新增异常！');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    });
}

/**
 * 一键领取客户
 */
function receiveCustomer(customerId, customerPoolId) {
    $.alert({
        title: '提示',
        content: "确定要领取吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerController/receiveCustomer",
                        data: {
                            customerId: customerId,
                            customerPoolId: customerPoolId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.data == 'C00001') {
                                $.alert('该客户不能领取!');
                            } else if (data.data == 'C00002') {
                                $.alert('您的客户容量已满,不能领取!');
                            } else if (data.data == 'C00003') {
                                $.alert('超过该客户池最大领取量,不能领取!');
                            } else if (data.data == 'C00004') {
                                $.alert('该客户暂不能领取!');
                            } else if (data.data == 'C00005') {
                                $.alert('客户领取过于频繁!');
                            } else if (data.data == 'C00007') {
                                $.alert('该客户暂不能领取!');
                            } else if (data.data == 'C00008') {
                                $.alert('客户已锁定!');
                            } else if (data.data == 'C00006') {
                                $.alert({
                                    title: '提示',
                                    content: '领取成功！',
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'btn-primary',
                                            action: function () {
                                                openTab("我的客户", "/front/customerManager/myCustomerPool");
                                                // 提交完表单，重新加载相关table列表页面
                                                refreshActivePane('/front/customerManager/myCustomerPool');
                                                $('#customerNameSearch').val('');
                                                $('#addSingleProductCustomerModel').modal('hide');
                                                $singleProductCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                                            }
                                        }
                                    }
                                });
                            } else {
                                $.alert('领取失败，请稍后再试!');
                            }
                        },
                        error: function () {
                            $.alert('领取异常，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

function customerDetail (customerId,singleProductCustomerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '单品客户详情',
        url : "/front/user/customerManager/userSingleProductCustomerDetail?customerId=" + customerId +"&singleProductCustomerId=" + singleProductCustomerId
    }, true);
}

//删除单品客户
function deleteSingleProductCustomer(singleProductCustomerId) {
    $.alert({
        title: '提示',
        content: "确定要删除吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/singleProductCustomer/deleteSingleProductCustomer",
                        data: {
                            singleProductCustomerId: singleProductCustomerId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('删除成功!');
                                $singleProductCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert('删除失败!');
                            }
                        },
                        error: function () {
                            $.alert('删除失败，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}